import { useState, useEffect } from 'react'
import { Select, Spin, Empty, message } from 'antd'
import _ from 'lodash'
import style from './index.module.less'
import { getArbitratorRequest } from './ajax'
import { ArbitratorSchema } from '../schema/arbitrator'
import { awaitWrap } from '@src/assets/js/tool'
const { Option } = Select

async function getOptions (s: string, setLoading: (v: boolean) => void, setOptions: (v: ArbitratorSchema[]) => void) {
  setLoading(true)
  const [e, d] = await awaitWrap(getArbitratorRequest([{ k: 'name', o: 'like', v: `%${s}%` }], 1, 10))
  setLoading(false)
  if (e === null && d !== null) {
    setOptions(d.list)
  }
}

async function getOptionsById (id: string | undefined, setLoading: (v: boolean) => void, setOptions: (v: ArbitratorSchema[]) => void) {
  setLoading(true)
  const [e, d] = await awaitWrap(getArbitratorRequest([{ k: 'id', o: '=', v: id }], 1, 10))
  setLoading(false)
  if (e === null && d !== null) {
    setOptions(d.list)
  }
}
const searchFn = _.debounce(getOptions, 500, { leading: false })

// 渲染空的情况
function renderEmpty (loading: boolean) {
  if (loading) {
    return (
      <div className={style.empty}><Spin /></div>
    )
  }
  return <div className={style.empty}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></div>
}


interface Props {
  value?: string
  onChange?: (v: string) => void
}

function Main ({ value, onChange = () => {} }: Props) {
  const [loading, setLoading] = useState(false)
  const [options, setOptions] = useState<ArbitratorSchema[]>([])
  useEffect(() => {
    getOptionsById(value, setLoading, setOptions)
  }, [value])
  return (
    <div className={style.container}>
      <Select defaultActiveFirstOption={false} filterOption={false} value={value} onChange={(v) => onChange(v)} placeholder='请选择仲裁员' showSearch allowClear onSearch={(v) => searchFn(v, setLoading, setOptions)} notFoundContent={renderEmpty(loading)}>
        {
          options.map((li, i) => {
            return <Option key={`${li.id}_${i}`} value={li.id}>{li.name}</Option>
          })
        }
      </Select>
    </div>
  )
}

export default Main
